package org.icec.gen.core;

import java.io.IOException;

import org.beetl.core.Template;
import org.beetl.sql.core.db.TableDesc;
import org.beetl.sql.core.kit.StringKit;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ControllerCodeGen implements   CodeGen{
	String CR = System.getProperty("line.separator");
	String pkg = null;
	String module="";
	public ControllerCodeGen() {
		super();
	}

	public ControllerCodeGen(String pkg) {
		super();
		this.pkg =pkg+".controller";
		String [] pkgArr = pkg.split("\\.");
		module = pkgArr[pkgArr.length-1];
	}
	public static String serviceTemplate = "";
	static {
		serviceTemplate = GenConfig.getTemplate("/org/icec/gen/core/controller.btl");
	}
	@Override
	public void genCode(String project, String entityPkg, String entityClass, TableDesc tableDesc, GenConfig config,
			boolean isDisplay) {
		if(pkg==null){
			pkg = entityPkg;
		}
		Template template = SourceGen.gt.getTemplate(serviceTemplate);
		String ctrlClass = entityClass+"Ctrl";
		String serviceClassType =entityClass+"Service";
		String serviceClassName =StringKit.toLowerCaseFirstOne(entityClass)+"Service";
		template.binding("className", ctrlClass);
		template.binding("package",pkg);
		template.binding("module",module);
		template.binding("entityClass", entityClass);
		template.binding("entityClassName", StringKit.toLowerCaseFirstOne(entityClass));
		template.binding("serviceClassType", serviceClassType);
		template.binding("serviceClassName", serviceClassName);
		String mapperHead = "import "+entityPkg+"."+entityClass+";"+CR;
		String servicepkg=pkg.replace("controller", "service");
		  mapperHead+="import "+servicepkg+"."+serviceClassType+";"+CR;
		template.binding("imports", mapperHead);
		String mapperCode = template.render();
		if(isDisplay){
			System.out.println();
			System.out.println(mapperCode);
		}else{
			try {
				SourceGen.saveSourceFile(project, pkg, ctrlClass, mapperCode);
			} catch (IOException e) {
				throw new RuntimeException("controller代码生成失败",e);
			}
		}
		log.info("controller succeed！");
		
	}

}
